package com.gt.quality.base;

import cn.idev.excel.FastExcel;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.gt.quality.base.pojo.BaseLimitRequest;
import com.gt.quality.base.pojo.Resp;
import com.gt.quality.config.SpringBeanUtil;
import com.gt.quality.system.entity.SysFileInfo;
import com.gt.quality.system.service.GTBaseService;
import com.gt.quality.system.service.SysFileInfoService;
import com.gt.quality.system.service.excel.BaseExcelInputListener;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.List;

/**
 * @author Administrator
 */
public interface BaseCommonService<T> extends GTBaseService<T> {


    /**
     * Description:  分页查询
     *
     * @param limitRequest 分页查询参数
     * @author: makeJava
     * @date: 2026-11-25 16:30:08
     * @return:com.baomidou.mybatisplus.core.metadata.IPage
     */
    default IPage<T> queryLimitPage(BaseLimitRequest<T> limitRequest) {
        T requestBody = limitRequest.getRequestBody();
        IPage<T> page = getByPageParam(limitRequest);
        JSONObject thisObj = JSONObject.from(requestBody);
        QueryWrapper<T> queryWrapper = queryWrapperBuilder(thisObj, limitRequest);
        return getBaseMapper().selectPage(page, queryWrapper);
    }


    /**
     * Description:  批量新增
     *
     * @param entityList entityList
     * @author: makeJava
     * @date: 2026-11-25 16:30:08
     * @return:Integer
     */
    Integer saveBatchByEasyBaseMapper(List<T> entityList);

    /**
     * Excel导入
     *
     * @param multipartFile 文件
     * @return Resp
     */
    default Resp<SysFileInfo> excelInput(MultipartFile multipartFile) {
        // 检查上传的文件是否为空
        if (multipartFile.isEmpty()) {
            throw new IllegalArgumentException("上传的文件不能为空");
        }
        // EasyExcel 读取Excel文件里的内容到List
        try (InputStream inputStream = multipartFile.getInputStream()) {
            BaseMapper<T> mapper = getBaseMapper();
            BaseExcelInputListener<T> listener = new BaseExcelInputListener<>(mapper);
            // 使用EasyExcelFactory读取输入流中的数据，映射到SysUser类，并使用SysUserExcelInputListener监听并处理读取到的数据
            FastExcel.read(inputStream, getEntityClass(), listener).sheet().doRead();
        } catch (Exception e) {
            // 记录错误日志，并抛出自定义异常，指示用户导入失败
            throw new BusinessSelfException("用户导入失败,请联系管理员");
        }
        SysFileInfoService bean = SpringBeanUtil.getBean(SysFileInfoService.class);

        // 保存文件信息
        return Resp.ok(bean.saveFileInfo(multipartFile));
    }
}
